package com.iplant.base.utils.tasker;

import com.iplant.base.po.BPMResource;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;

@Slf4j
public class TaskHandleBase {

    public String HandleString = "";
    public BPMResource<Runnable> Resource;

    public volatile  boolean Active = false;

    public volatile  boolean Alive = false;

    public int SleepTime = 10000;

    public TaskHandleBase() {
    }


    public TaskHandleBase(String wHandleString, BPMResource<Runnable> wResource) {
        this.HandleString = wHandleString;
        this.Resource = wResource;
    }

    public TaskHandleBase(String wHandleString) {
        this.HandleString = wHandleString;
        this.Resource = new BPMResource<Runnable>(Runnable.class, wHandleString);
    }

    public TaskHandleBase(String wHandleString, int wSleepTime) {
        this.HandleString = wHandleString;
        this.Resource = new BPMResource<Runnable>(Runnable.class, wHandleString);
        this.SleepTime = wSleepTime;
    }

    public TaskHandleBase(String wHandleString, BPMResource<Runnable> wResource, int wSleepTime) {
        this.HandleString = wHandleString;
        this.Resource = wResource;
        this.SleepTime = wSleepTime;
    }

    public void Add(Runnable wRunnable) {
        if (Resource != null)
            Resource.add(wRunnable);
    }

    public void Run() {
        try {
            if (Active || Resource == null)
                return;
            Active = true;
            Alive = true;

            new Thread(() -> {
                Calendar wNow;
                while (Alive) {
                    try {
                        Runnable wRunnable = Resource.get();
                        if (wRunnable != null)
                            wRunnable.run();

                        Thread.sleep(SleepTime);
                    } catch (Exception ex) {
                        log.error("Run while" + HandleString, ex);
                    }
                }
            }).start();
        } catch (Exception ex) {
            log.error("Run " + HandleString, ex);
        }
    }



    public void destroy() {
        Alive = false;
    }
}
